package com.wash.shoes.controller.pc;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Lists;
import com.lop.open.api.sdk.LopException;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.CustomIdGenerator;
import com.wash.shoes.common.enums.FulFillEnum;
import com.wash.shoes.common.enums.OrderStatusEnum;
import com.wash.shoes.domain.dto.*;
import com.wash.shoes.domain.dy.request.DyBookRequest;
import com.wash.shoes.domain.dy.request.DyServiceUpdateRequest;
import com.wash.shoes.domain.jd.JdCreateOrder;
import com.wash.shoes.domain.mtbusy.MtUpdateFulFillInfo;
import com.wash.shoes.domain.vo.AddOrderVo;
import com.wash.shoes.domain.vo.OrderDetailVo;
import com.wash.shoes.domain.vo.ShoeVo;
import com.wash.shoes.entity.*;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.helper.FactoryAddressHelper;
import com.wash.shoes.mapper.CustomerMapper;
import com.wash.shoes.mapper.FactoryShelvesMapper;
import com.wash.shoes.mapper.WorkOrderMapper;
import com.wash.shoes.request.CorrectOrderRequest;
import com.wash.shoes.request.GetWashCodeResp;
import com.wash.shoes.request.OrderStatisRequest;
import com.wash.shoes.request.RemoveShoeRequest;
import com.wash.shoes.resp.SingleOrderStatisResp;
import com.wash.shoes.service.*;
import com.wash.shoes.service.impl.AccessoriesServiceImpl;
import com.wash.shoes.service.impl.QualityInspectionServiceImpl;
import com.wash.shoes.util.AdminUserUtil;
import com.wash.shoes.util.CodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author ljg
 * @since 2024-08-29
 */
@Log4j2
@Api(tags = {"PC-洗护订单"})
@RestController
@RequestMapping({"/dev-api/order", "/order"})
public class OrderController extends BaseController {

    @Autowired
    OrderService orderService;

    @Autowired
    ShoeRackGridService shoeRackGridService;

    @Autowired
    ShoeService shoeService;

    @Autowired
    ShopGoodsService shopGoodsService;

    @Autowired
    OrderGoodService orderGoodService;

    @Autowired
    ShopService shopService;

    @Autowired
    ShoeRackService shoeRackService;

    @Autowired
    OrderTransportService orderTransportService;

    @Autowired
    JdCreateOrder jdCreateOrder;

    @Autowired
    MtUpdateFulFillInfo mtUpdateFulFillInfo;

    @Autowired
    DyServiceUpdateRequest serviceUpdateRequest;

    @Autowired
    DyServiceUpdateRequest dyServiceUpdateRequest;

    /**
     * redisClient
     */
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private FactoryshelvesRackGridService factoryshelvesRackGridService;
    @Autowired
    private FactoryShelvesMapper factoryShelvesMapper;
    @Autowired
    private FactoryShelvesService factoryShelvesService;
    @Autowired
    private FactoryAddressHelper factoryAddressHelper;
    @Value("${onLineDateTime}")
    private String onLineDateTime;
    @Autowired
    private FactoryService factoryService;

    /**
     * 检测是否是新订单,在上线时间后的订单
     *
     * @param createOrderTime 订单创建时间
     * @return
     */
    private boolean isNewOrder(Date createOrderTime) {
        Assert.notNull(createOrderTime, "订单创建时间不能为空");
        // String onLineDateTime = "2025-08-31 10:00:00";
        return DateUtil.parse(onLineDateTime, "yyyy-MM-dd HH:mm:ss").before(createOrderTime);
    }

    @ApiOperation("获取订单列表")
    @PostMapping("/list")
    public R<Page<OrderDetailVo>> pageList(@RequestBody OrderPageListDto orderPo) {
        Page<OrderDetailVo> page;
        OrderPo orderPoWashCode = getOrderByWashCode(orderPo.getKeywords(), orderPo.getStatus());
        if (orderPoWashCode != null) {
            page = new Page<>();
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            BeanUtils.copyProperties(orderPoWashCode, orderDetailVo);
            page.setRecords(Collections.singletonList(orderDetailVo));
            page.setTotal(1);
            return R.ok(page);
        }
        page = orderService.pageList(orderPo);
        page.getRecords().forEach(e -> {
            //查询这个订单是否有未完结的工单
            long processNode = workOrderMapper.selectCount(new LambdaQueryWrapper<WorkOrderPo>().eq(WorkOrderPo::getOrderId, e.getId()).eq(WorkOrderPo::getStatus, "0"));
            //只要订单状态不是取消状态或者工单不是进行中状态都可以在后面有个按钮叫创建工单
            if (!OrderStatusEnum.CANCEL.getStatus().equals(e.getStatus()) && processNode == 0) {
                e.setHasWorkOrder(1);
            }
        });
        return R.ok(page);
    }

    @Autowired
    private WorkOrderMapper workOrderMapper;

    /**
     * @author lijianguo
     * @Date 28/09/2024 请输入方法的简介
     **/
    private OrderPo getOrderByWashCode(String keywords, Integer status) {
        if (keywords != null) {
            ShoeVo shoeVo = shoeService.shoeDetailByWashCode(keywords);
            if (shoeVo != null) {
                OrderPo orderNew = orderService.getById(shoeVo.getOrderId());
                if (orderNew.getStatus().equals(status)) {
                    return orderNew;
                }
            }
        }
        return null;
    }

    @ApiOperation("修改新增订单,有id为修改没有为新增,pc的订单到店的订单")
    @PostMapping("/pcSaveUpdate")
    @Transactional
    public R<OrderPo> pcSaveUpdate(@RequestBody AddOrderVo addOrderVo) {
        CodeUtil.clearCurrentCacheCode();
        if (ObjectUtil.isEmpty(addOrderVo.getId())) {

            ShopPo shopPo = shopService.getById(addOrderVo.getShopId());
            Assert.notNull(shopPo, "店铺不存在.shopId:" + addOrderVo.getShopId());
            FactoryPo factoryPo = factoryAddressHelper.getFactoryAddressWithShopAddress(shopPo.getProvincesName(), shopPo.getCityName(), shopPo.getCountryName(), shopPo.getBrandId());
            // 获取分布式锁,全局分布式锁key
            RLock lock = null;
            String lockKey = "shoeRack:lock" + factoryPo.getId();
            try {
                lock = redissonClient.getLock(lockKey);
                boolean isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
                if (!isLocked) {
                    log.error("获取分布式锁失败,工厂ID：" + factoryPo.getId());
                    return R.fail("新增订单失败，请稍后重试");
                }
                log.info("线下订单入库获取到分布式锁,工厂ID：" + factoryPo.getId());

                // 添加订单
                /*  List<ShoeRackGridPo> shoeRackGridPoList =
                    shoeRackGridService.shareGridList(addOrderVo.getShoesNum(), addOrderVo.getShopId());
                if (shoeRackGridPoList.isEmpty()) {
                    throw new WashException("鞋架已经用完,不能分配鞋架");
                }*/
                // 获取数据库的店铺
                ShopPo shopDb = shopService.getById(addOrderVo.getShopId());
                if (shopDb == null) {
                    throw new WashException("门店不存在，请检查门店");
                }
                // 订单，pc到店的订单初始化状态应该是清洗中
                OrderPo orderPo = new OrderPo();
                BeanUtils.copyProperties(addOrderVo, orderPo);
                orderPo.setShoeNum(addOrderVo.getShoesNum());
                // 订单是带入库 鞋子是待清洗
                orderPo.setStatus(OrderStatusEnum.PENDING_STORAGE.getStatus());
                if (StrUtil.isNotBlank(addOrderVo.getPre())) {
                    orderPo.setOrderNo(CodeUtil.getOrderCodeNext(addOrderVo.getPre(), shopDb.getId(), shopDb.getShopCode()));
                } else {
                    orderPo.setOrderNo(CodeUtil.getOrderCodeNext("O", shopDb.getId(), shopDb.getShopCode()));
                }
                log.info("oder code is {}", orderPo.getOrderNo());
                orderService.save(orderPo);
                // 鞋子添加鞋架的编号
                List<ShoePo> tempShoeList = new ArrayList<>();
                // 获取工厂的架子格子
                List<FactoryshelvesRackGridPo> factoryshelvesRackGridPoList =
                        factoryshelvesRackGridService.shareGridList(1, factoryPo.getId(), orderPo.getId());
                // 同一个订单放同一个格子
                for (int i = 0; i < orderPo.getShoeNum(); i++) {
                    // ShoeRackGridPo shoeRackGridPo = shoeRackGridPoList.get(i);
                    FactoryshelvesRackGridPo shoeRackGridPo = factoryshelvesRackGridPoList.get(0);
                    ShoePo shoePo = new ShoePo();
                    shoePo.setSrgId(shoeRackGridPo.getId());
                    shoePo.setSrgCode(shoeRackGridPo.getShowCode());
                    shoePo.setShopId(addOrderVo.getShopId());
                    String nextCode = CodeUtil.getWashCodeNext(shopDb.getId(), shopDb.getShopCode());
                    log.info("wash code is {}", nextCode);
                    shoePo.setWashCode(nextCode);
                    // 定单号的生成规则
                    shoePo.setOrderNumber(orderPo.getOrderNo());
                    shoePo.setOrderId(orderPo.getId());
                    shoePo.setWashType(null);
                    // 待清洗
                    shoePo.setStatus(0);
                    shoePo.setPhone(addOrderVo.getCustomPhone());
                    shoePo.setStorageTime(new Date());
                    shoePo.setStorageUser(AdminUserUtil.getUserId());
                    shoePo.setStorageUserName(AdminUserUtil.getLoginUserName());
                    tempShoeList.add(shoePo);
                }
                shoeService.saveBatch(tempShoeList);
                // 设置鞋架的鞋子
                // TODO: 2024/9/1：线下洗才会走add添加订单。 订单自动通过定时任务从美团、抖音拉取来的，进行保存订单时，这里应该不用分配鞋子的鞋架号、水洗码，只有在入库以后才去生成
                /* for (int i = 0; i < tempShoeList.size(); i++) {
                    ShoeRackGridPo shoeRackGridPo = shoeRackGridPoList.get(i);
                    ShoePo shoePo = tempShoeList.get(i);
                    shoeRackGridPo.setShoeId(shoePo.getId());
                }*/
                // 把格子和订单id绑定.
                FactoryshelvesRackGridPo factoryshelvesRackGridPo = factoryshelvesRackGridPoList.get(0);
                factoryshelvesRackGridPo.setOrderId(tempShoeList.get(0).getOrderId());
                factoryshelvesRackGridService.updateById(factoryshelvesRackGridPo);

                // shoeRackGridService.updateBatchById(shoeRackGridPoList);
                // 设置订单的商品
                List<OrderGoodPo> orderGoodPoList = new ArrayList<>(addOrderVo.getOrderGoodPoList().size());
                for (OrderGoodPo shopGoodsPo1 : addOrderVo.getOrderGoodPoList()) {
                    ShopGoodsPo shopGoodsPo = shopGoodsService.getById(shopGoodsPo1.getGoodsId());
                    OrderGoodPo po = new OrderGoodPo();
                    po.setCustomId(addOrderVo.getCustomId());
                    po.setShopId(addOrderVo.getShopId());
                    po.setName(shopGoodsPo.getName());
                    po.setPrice(shopGoodsPo.getPrice());
                    po.setBuyNum(shopGoodsPo1.getBuyNum());
                    po.setShopGoodsUrl(shopGoodsPo.getUrl());
                    po.setGoodsId(shopGoodsPo1.getGoodsId());
                    po.setShoesNum(shopGoodsPo.getShoesNum());
                    po.setOrderId(orderPo.getId());
                    orderGoodPoList.add(po);
                }
                orderGoodService.saveOrUpdateBatch(orderGoodPoList);
                // 更新鞋架的使用数量
                // shoeRackService.updateUseNum(shoeRackGridPoList);
                // 根据货架id去更新货架的使用数量
                factoryShelvesService.updateUseNumInteger(factoryshelvesRackGridPoList.get(0).getFactoryshelvesId());
                return R.ok(orderPo);
            } catch (Exception e) {
                throw new WashException("新增订单失败: " + e.getMessage(), e);
            } finally {
                if (lock != null && lock.isHeldByCurrentThread()) {
                    lock.unlock(); // 释放锁
                }
            }
        }
        return R.ok(null);
    }

    @ApiOperation("获取订单的详情")
    @GetMapping("/getOrderDetail")
    public R<OrderDetailVo> getOrderDetail(String orderId) {

        OrderPo orderPo = orderService.getById(orderId);
        if (Objects.nonNull(orderPo.getBrandId())) {
            BrandPo brandPo = brandService.getById(orderPo.getBrandId());
            orderPo.setSelfOperated(brandPo.getSelfOperated());
        }
        if (OrderStatusEnum.PRE_PAY.getStatus().equals(orderPo.getStatus()) && "3".equals(orderPo.getComeFrom())) {
            DateTime date = DateUtil.parse(orderPo.getMtBeginTime(), "yyyy-MM-dd HH:mm:ss");
//            DateTime date = DateUtil.parse("2025-09-25 19:30:00", "yyyy-MM-dd HH:mm:ss");
//            System.out.println(date.after(DateTime.now()));
            // 预约时间应该晚于当前时间
            if (date.before(DateTime.now())) {
                orderPo.setStatus(OrderStatusEnum.CANCEL.getStatus());//预约时间已经过期,就把status设置成已取消
                orderService.updateById(orderPo);
            }
        }

        OrderDetailVo orderDetailVo = new OrderDetailVo();
        BeanUtils.copyProperties(orderPo, orderDetailVo);
        List<OrderGoodPo> orderGoodPoList = orderGoodService.getOrderGoods(orderId);
        orderDetailVo.setOrderGoodPoList(orderGoodPoList);
        List<ShoePo> shoePoList = shoeService.getByOrderId(orderId);
        //填充物品的配饰信息
        shoePoList.forEach(e -> {
            if (Objects.isNull(e.getQualityInspectorStatus())) {
                e.setQualityInspectorStatus("0");
            }
            //根据订单id和物品id查询对应的配饰数据
            List<AccessoriesPo> accessoriesPoList = accessoriesService.list(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, e.getOrderId()).eq(AccessoriesPo::getBizId, e.getId()));
            if (CollectionUtil.isNotEmpty(accessoriesPoList)) {
                //转换填充配饰信息
                e.setAccessorVoList(accessoriesPoList.stream().map(accessoriesPo -> {
                    ShoePo.AccessorVo accessorVo = new ShoePo.AccessorVo();
                    accessorVo.setType(accessoriesPo.getType());
                    accessorVo.setWashCode(accessoriesPo.getWashCode());
                    accessorVo.setStatus(accessoriesPo.getStatus());
                    accessorVo.setId(accessoriesPo.getId());
                    return accessorVo;
                }).collect(Collectors.toList()));
            }
        });
        orderDetailVo.setShoePoList(shoePoList);
        // 物流信息
        List<OrderTransportPo> orderTransportPoList = orderTransportService.getByOrderId(orderId);
        orderDetailVo.setOrderTransportPoList(orderTransportPoList);

        OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderIdType(orderId, "取鞋");
        if (Objects.nonNull(orderTransportPo)) {
            orderDetailVo.setReceiverAddress(orderTransportPo.getSendFullAddress()); //修改by jjz 2025年10月31日 19:37:13 反馈说地址显示错误,这里修改下看看
            orderDetailVo.setReceiverName(orderTransportPo.getSendName());
            orderDetailVo.setReceiverMobile(orderTransportPo.getSendMobile());
            //如果订单上有就表示是修改过的地址,就优先取这个地址
            if (StringUtils.isNotEmpty(orderPo.getTransJson())) {
                try {
                    MobileOrderDto mobileOrder = com.alibaba.fastjson2.JSONObject.parseObject(orderPo.getTransJson(), MobileOrderDto.class);
                    orderDetailVo.setReceiverName(mobileOrder.getSendBackUserAddress().getReceiverName());
                    orderDetailVo.setReceiverMobile(mobileOrder.getSendBackUserAddress().getReceiverMobile());
                    orderDetailVo.setReceiverAddress(mobileOrder.getSendBackUserAddress().getReceiverAddress());
                } catch (Exception e) {
                }
            }
        }
        return R.ok(orderDetailVo);
    }

    @ApiOperation("获取订单的详情订单号")
    @GetMapping("/getOrderDetailByNo")
    public R<OrderDetailVo> getOrderDetailByNo(String orderNo) {

        OrderPo orderPo = orderService.getByOrderNo(orderNo);
        if (Objects.nonNull(orderPo.getBrandId())) {
            BrandPo brandPo = brandService.getById(orderPo.getBrandId());
            orderPo.setSelfOperated(brandPo.getSelfOperated());
        }
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        BeanUtils.copyProperties(orderPo, orderDetailVo);
        List<OrderGoodPo> orderGoodPoList = orderGoodService.getOrderGoods(orderPo.getId());
        orderDetailVo.setOrderGoodPoList(orderGoodPoList);
        List<ShoePo> shoePoList = shoeService.getByOrderId(orderPo.getId());
        orderDetailVo.setShoePoList(shoePoList);

        // 物流信息
        List<OrderTransportPo> orderTransportPoList = orderTransportService.getByOrderId(orderPo.getId());
        orderDetailVo.setOrderTransportPoList(orderTransportPoList);
        OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "取鞋");
        if (Objects.nonNull(orderTransportPo)) {
            orderDetailVo.setReceiverAddress(orderTransportPo.getSendFullAddress());
        }
        return R.ok(orderDetailVo);
    }

    @Autowired
    private BrandService brandService;
    @Autowired
    private CustomerMapper customerMapper;

    /**
     * @author lijianguo
     * @Date 20/09/2024 订单号,物流单号，水洗码 查询订单
     **/

    @ApiOperation("获取订单的详情订by订单号,物流单号,水洗码")
    @GetMapping("/getOrderDetailUesMulType")
    public R<OrderDetailVo> getOrderDetailUesMulType(String searchInfo) {

        // 控制
        if (StrUtil.isNotEmpty(searchInfo) && searchInfo.startsWith("JD")) {
            String[] dataList = searchInfo.split("-");
            searchInfo = dataList[0];
        }

        // 订单号查询
        OrderPo orderPo = orderService.getByOrderNo(searchInfo);
        if (orderPo == null) {
            // 物流单号查询
            OrderTransportPo orderTransportPo = orderTransportService.getByWayBillCode(searchInfo);
            if (orderTransportPo != null) {
                orderPo = orderService.getById(orderTransportPo.getOrderId());
            }
        }
        // 水洗码查询
        if (orderPo == null) {
            ShoeVo shoeVo = shoeService.shoeDetailByWashCode(searchInfo);
            if (shoeVo != null) {
                orderPo = orderService.getById(shoeVo.getOrderId());
            }
        }
        // 按照电话查询
        if (orderPo == null) {
            orderPo = orderService.getLastByPhone(searchInfo);
        }
        if (orderPo == null) {
            AccessoriesPo accessoriesPo1 = accessoriesService.getOne(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getWashCode, searchInfo));
            if (Objects.nonNull(accessoriesPo1) && Objects.nonNull(accessoriesPo1.getOrderId())) {
                orderPo = orderService.getById(accessoriesPo1.getOrderId());
            }
        }

        if (orderPo == null) {
            throw new WashException("订单信息不存在,请仔细检查: " + searchInfo);
        }

        if (Objects.nonNull(orderPo.getCustomId())) {
            CustomerPo customerPo = customerMapper.selectById(orderPo.getCustomId());
            if (Objects.nonNull(customerPo)) {
                orderPo.setCustomName(customerPo.getName());
            }
        }
        if (Objects.nonNull(orderPo.getBrandId())) {
            BrandPo brandPo = brandService.getById(orderPo.getBrandId());
            if (Objects.nonNull(brandPo)) {
                //增加返回品牌是否自营
                orderPo.setSelfOperated(brandPo.getSelfOperated());
            }
        }


        //填充是否是自营品牌
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        BeanUtils.copyProperties(orderPo, orderDetailVo);
        List<OrderGoodPo> orderGoodPoList = orderGoodService.getOrderGoods(orderPo.getId());
        orderDetailVo.setOrderGoodPoList(orderGoodPoList);
        List<ShoePo> shoePoList = shoeService.getByOrderId(orderPo.getId());
        if (CollectionUtil.isNotEmpty(shoePoList)) {
            AtomicInteger index = new AtomicInteger(0);

            //填充物品的配饰信息
            shoePoList.forEach(e -> {
                if (Objects.isNull(e.getQualityInspectorStatus())) {
                    e.setQualityInspectorStatus("0");
                }
                e.setIndex(index.addAndGet(1) + "/" + shoePoList.size());
                e.setComplete(index.get() == shoePoList.size() ? "齐" : "");
                //根据订单id和物品id查询对应的配饰数据
                List<AccessoriesPo> accessoriesPoList = accessoriesService.list(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, e.getOrderId()).eq(AccessoriesPo::getBizId, e.getId()));
                if (CollectionUtil.isNotEmpty(accessoriesPoList)) {
                    //转换填充配饰信息
                    e.setAccessorVoList(accessoriesPoList.stream().map(accessoriesPo -> {
                        ShoePo.AccessorVo accessorVo = new ShoePo.AccessorVo();
                        accessorVo.setType(accessoriesPo.getType());
                        accessorVo.setWashCode(accessoriesPo.getWashCode());
                        accessorVo.setStatus(accessoriesPo.getStatus());
                        accessorVo.setId(accessoriesPo.getId());
                        return accessorVo;
                    }).collect(Collectors.toList()));
                }
            });
        }

        // 需要修改货架号
        // FactoryshelvesRackGridPo factoryshelvesRackGridPo=factoryshelvesRackGridService.getOne(new
        // LambdaQueryWrapper<FactoryshelvesRackGridPo>().eq(StringUtils.isNotBlank(orderPo.getId()),
        // FactoryshelvesRackGridPo::getOrderId,orderPo.getId()));
        // if(factoryshelvesRackGridPo==null){
        // throw new WashException("根据订单号没有查询到货架号"+orderPo.getId());
        // }
        // shoePoList.forEach(res-> res.setSrgCode(factoryshelvesRackGridPo.get));
        orderDetailVo.setShoePoList(shoePoList);

        // 物流信息
        List<OrderTransportPo> orderTransportPoList = orderTransportService.getByOrderId(orderPo.getId());
        orderDetailVo.setOrderTransportPoList(orderTransportPoList);
        OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "取鞋");
        if (Objects.nonNull(orderTransportPo)) {
            orderDetailVo.setReceiverAddress(orderTransportPo.getSendFullAddress());
        }
        List<OrderDetailVo> data1 = Lists.newArrayList();
        data1.add(orderDetailVo);
        //填充商品信息和物流单号
        orderService.setBillCodeName(data1);
        orderService.setGoodSNames(data1);
        return R.ok(orderDetailVo);
    }

    @Autowired
    private AccessoriesServiceImpl accessoriesService;

    /**
     * @author lijianguo
     * @Date 01/09/2024 订单出库：待出库的订单可以出库，线下订单只修改订单的状态为已完成,不做其他处理
     **/
    @ApiOperation("订单出库PC(线下)多个逗号分隔，不需要发快递")
    @GetMapping("/pcStockOut")
    @Transactional
    public R<Boolean> pcStockOut(String... orderIds) {
        for (String orderId : orderIds) {
            OrderPo orderPo = orderService.getById(orderId);
            // 待出库
            if (!Objects.equals(orderPo.getStatus(), OrderStatusEnum.PENDING_OUTBOUND.getStatus())) {
                throw new WashException("不是待出库的订单");
            }
            orderPo.setStatus(OrderStatusEnum.COMPLETED.getStatus());
            orderPo.setCheckOutPerson(AdminUserUtil.getLoginUserName());
            orderPo.setCheckOutTime(new Date());
            // 释放鞋架
            releasesGrid(orderId);
            orderService.updateById(orderPo);
            // 这个需要判断订单是不是mt的订单，mt的订单需要更新履约的状态,需要更新为
            if (orderPo.getComeFrom().equals("2")) {
                log.info("更新美团的物流信息为 [返回中(洗衣)]");
                mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.RETURNING, "刷鞋匠", "13892920924");
                log.info("更新美团的物流信息为 [履约完成(通用)]");
                mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.COMPLETION, "刷鞋匠", "13892920924");
            }
            // 抖音的订单
            if (orderPo.getComeFrom().equals("3")) {
                log.info("更新抖音的订单的状态为[服务完成]");
                serviceUpdateRequest.updateFullFill(orderPo, 4);
            }

        }
        return R.ok(true);
    }

    /**
     * @author lijianguo
     * @Date 01/09/2024 线上出库：需要预约的时间,出库以后需要生产jd的物流信息然后 到运输中
     **/
    @ApiOperation("线上出库，需要发快递")
    @PostMapping("/onlineStockOut")
    @Transactional
    public R<List<String>> onlineStockOut(@RequestBody List<OnlineStockOutDto> onlineStockOutDtoList) {

        List<String> userTrans = new ArrayList<>();
        for (OnlineStockOutDto onlineStockOutDto : onlineStockOutDtoList) {

            OrderTransportPo orderTransportPo =
                    orderTransportService.getOneByOrderIdType(onlineStockOutDto.getOrderId(), "取鞋");
            MtUserAddress mtUserAddress = JSONObject.parseObject(orderTransportPo.getDeliveryJson(), MtUserAddress.class);
            if (mtUserAddress == null) {
                //在次从物流表中获取用户地址（兼容反洗订单）
                String sendFullAddress = orderTransportPo.getSendFullAddress();
                if (StringUtils.isBlank(sendFullAddress)) {
                    throw new WashException("用户地址不存在");
                }
                mtUserAddress = new MtUserAddress();
                mtUserAddress.setReceiverMobile(orderTransportPo.getSendMobile());
                mtUserAddress.setReceiverAddress(orderTransportPo.getSendFullAddress());
                mtUserAddress.setReceiverName(orderTransportPo.getSendName());
            }
            //如果单独填写了收件地址 就用填写的收件地址
            if (StringUtil.isNotEmpty(onlineStockOutDto.getReceiverAddress())) {
                mtUserAddress.setReceiverAddress(onlineStockOutDto.getReceiverAddress());
                //把新填的地址变更给他保存回去
                orderTransportPo.setDeliveryJson(JSONObject.toJSONString(mtUserAddress));
                orderTransportService.updateById(orderTransportPo);
            }

            String orderId = onlineStockOutDto.getOrderId();
            log.info("orderTransportPo is not null");
            OrderPo orderPo = orderService.getById(orderId);
            // 待出库
            if (!Objects.equals(orderPo.getStatus(), OrderStatusEnum.PENDING_OUTBOUND.getStatus())) {
                throw new WashException("不是待出库的订单");
            }
            // 出库人,出库日期
            orderPo.setCheckOutPerson(AdminUserUtil.getLoginUserName());
            orderPo.setCheckOutTime(new Date());
            orderPo.setStatus(OrderStatusEnum.SENDING_SHOES.getStatus());

            // 释放鞋架
            releasesGrid(orderId);
            orderService.updateById(orderPo);
            // 添加物流信息
            ShopPo shopPo = shopService.getById(orderPo.getShopId());

            List<OrderGoodPo> orderGoods = orderGoodService.getOrderGoods(orderId);
            OrderGoodPo orderGoodPo = Optional.ofNullable(orderGoods).orElse(Lists.newArrayList()).stream().findFirst()
                    .orElse(new OrderGoodPo());
            /*    MtUserAddress shopAddress = new MtUserAddress();
            shopAddress.setReceiverName(shopPo.getShopName());
            shopAddress.setReceiverMobile(shopPo.getPhone());
            shopAddress.setReceiverAddress(shopPo.getAddress());*/

            // 现在都为工厂清洗,所以暂时未启用二次拆单
            // MtUserAddress shopAddress = AddressCuttingUtil.getDeliveryAddress(orderGoodPo,shopPo);

            // 下面方法逻辑为：如果把清洗工厂切换到另外一个工厂，但是上一个工厂未洗完，那么就整体用取鞋时候的收件地址作为出库时候的出库地址
            String receiverFullAddress = orderTransportPo.getReceiverFullAddress();
            MtUserAddress shopAddress = new MtUserAddress();
            // 修改出库的时候修改寄件人 by jjz
            if (Objects.nonNull(orderPo.getFactoryId())) {
                FactoryPo factoryPo = factoryService.getById(orderPo.getFactoryId());
                Assert.notNull(factoryPo, "工厂不存在:" + orderPo.getFactoryId());
                shopAddress.setReceiverName(factoryPo.getFactoryName());
                shopAddress.setReceiverMobile(factoryPo.getFactoryPhone());
            } else {
                shopAddress.setReceiverName(shopPo.getShopName());
                shopAddress.setReceiverMobile(shopPo.getPhone());
            }

            shopAddress.setReceiverAddress(receiverFullAddress);

            try {
                // DateTime dateTime = DateUtil.parse(onlineStockOutDto.getOderDate(),"yyyy-MM-dd HH:mm");
                long seconds = Long.parseLong(onlineStockOutDto.getOrderDate()) / 1000L;
                OrderTransportPo toUser = jdCreateOrder.process(orderPo, shopAddress, mtUserAddress, "送鞋", seconds);
                userTrans.add(toUser.getWayBillCode());
            } catch (LopException e) {
                log.error(e);
                throw new WashException(e.getMessage());
            }
            // 送鞋中
            serviceUpdateRequest.updateFullFill(orderPo, 3);
        }
        return R.ok(userTrans);
    }

    /**
     * @author lijianguo
     * @Date 04/09/2024 释放鞋架的位置
     **/
    private void releasesGrid(String orderId) {

        OrderPo orderPo = orderService.getById(orderId);
        // 增加判断在上线之前走老的出库逻辑
        // if (orderPo.getCreateTime().before(DateUtil.parse(onLineDateTime, "yyyy-MM-dd HH:mm:ss"))) {
        // 老订单走原来的释放逻辑
        if (!isNewOrder(orderPo.getCreateTime())) {
            // 老的出库的逻辑,
            List<ShoePo> allShoe = shoeService.getByOrderId(orderId);
            for (ShoePo shoePo : allShoe) {
                ShoeRackGridPo shoeRackGridPo = shoeRackGridService.getById(shoePo.getSrgId());
                // 相同的鞋子，才能释放
                if (shoeRackGridPo != null && shoePo.getId().equals(shoeRackGridPo.getShoeId())) {
                    shoeRackGridPo.setShoeId(null);
                    shoeRackGridService.updateById(shoeRackGridPo);
                }
            }
            // 计算鞋架的鞋子使用数量
            List<String> rackIds = allShoe.stream().map(ShoePo::getSrgId).distinct().collect(Collectors.toList());
            for (String rackId : rackIds) {
                shoeRackService.updateUseNumInteger(rackId);
            }
        } else {
            // 新的出库逻辑走工厂货架格子出库
            releasesGridNew(orderId);
        }
    }

    /**
     * 出库释放鞋架的资源
     *
     * @param orderId 订单id
     **/
    private void releasesGridNew(String orderId) {
        List<ShoePo> allShoe = shoeService.getByOrderId(orderId);
        Set<String> set = allShoe.stream().map(ShoePo::getSrgId).collect(Collectors.toSet());
        // 计算鞋架的鞋子使用数量
        List<FactoryshelvesRackGridPo> data =
                factoryshelvesRackGridService.list(new LambdaQueryWrapper<FactoryshelvesRackGridPo>()
                        .in(CollectionUtil.isNotEmpty(set), FactoryshelvesRackGridPo::getId, set).eq(FactoryshelvesRackGridPo::getOrderId, orderId));
        if (CollectionUtil.size(data) > 1 || CollectionUtil.size(data) == 0) {
            log.info("数据错误,一个订单应该是一个格子,或者此订单已经释放完货架了，订单id:{}", orderId);
            return;
        }
        FactoryshelvesRackGridPo factoryshelvesRackGridPo = data.get(0);

        // 设置格子的订单为null
        updateFactoryShevelsOrderId(factoryshelvesRackGridPo);
        // 修改货架的已使用数量
        factoryShelvesService.updateUseNumInteger(factoryshelvesRackGridPo.getFactoryshelvesId());
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean updateFactoryShevelsOrderId(FactoryshelvesRackGridPo factoryshelvesRackGridPo) {
        String orderId = factoryshelvesRackGridPo.getOrderId();
        factoryshelvesRackGridPo.setOrderId(null);
        // factoryshelvesRackGridService.updateById(factoryshelvesRackGridPo);
        int falg = factoryshelvesRackGridService.updateFactoryShevelsOrderIdWithId(factoryshelvesRackGridPo.getId());
        log.info("释放货架绑定的订单:{},falg:{},orderid:{}", factoryshelvesRackGridPo.getFactoryshelvesId(), falg, orderId);
        return SqlHelper.retBool(falg);
    }

    @ApiOperation(value = "单一订单统计", response = SingleOrderStatisResp.class)
    @GetMapping("/orderStatis")
    public R<SingleOrderStatisResp> getOrderStatis(@Valid OrderStatisRequest orderStatisRequest) {
        SingleOrderStatisResp singleOrderStatisResp = new SingleOrderStatisResp();
        //获取这个订单的物品
        List<ShoePo> data = shoeService.getByOrderId(orderStatisRequest.getOrderId());
        AtomicInteger clothesNum = new AtomicInteger();
        AtomicInteger shoesNum = new AtomicInteger();
        AtomicInteger otherNum = new AtomicInteger();
        if (CollectionUtil.isNotEmpty(data)) {
            data.forEach(e -> {
                if ("衣服".equals(e.getItemType())) {
                    clothesNum.getAndIncrement();
                } else if ("鞋子".equals(e.getItemType())) {
                    shoesNum.getAndIncrement();
                } else if (Objects.nonNull(e.getItemType())) {
                    otherNum.getAndIncrement();
                }
            });

            //衣服的数量
            singleOrderStatisResp.setClothesNum(clothesNum.get());
            singleOrderStatisResp.setShoesNum(shoesNum.get());
            //查询这个订单的配饰数量
            singleOrderStatisResp.setAccessorNum(accessoriesService.count(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, orderStatisRequest.getOrderId())));

            singleOrderStatisResp.setOtherNum(otherNum.get());
        }
        //查询这个订单绑定的格子
        FactoryshelvesRackGridPo factoryshelvesRackGridPo = factoryshelvesRackGridService.getOne(new LambdaQueryWrapper<FactoryshelvesRackGridPo>().eq(FactoryshelvesRackGridPo::getOrderId, orderStatisRequest.getOrderId()));
        if (Objects.nonNull(factoryshelvesRackGridPo)) {
            singleOrderStatisResp.setCode(factoryshelvesRackGridPo.getShowCode());
        }
        return R.ok(singleOrderStatisResp);
    }

    @ApiOperation(value = "移除物品")
    @PostMapping("/removeShoe")
    public R<Boolean> removeShoe(@RequestBody @Valid RemoveShoeRequest removeShoeRequest) {
        OrderPo orderPo = orderService.getById(removeShoeRequest.getOrderId());
        Assert.notNull(orderPo, "订单不存在");
        if (OrderStatusEnum.CLEANING_IN_PROCESS.getStatus() == orderPo.getStatus()) {
            return R.fail("订单正在清洗中，请勿删除");
        }
        shoeService.remove(new LambdaQueryWrapper<ShoePo>().eq(ShoePo::getId, removeShoeRequest.getShoeId()).eq(ShoePo::getOrderId, removeShoeRequest.getOrderId()));
        iAccessoriesService.remove(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, removeShoeRequest.getOrderId()).eq(AccessoriesPo::getBizId, removeShoeRequest.getShoeId()));

        //鞋子被删完的情况就需要
        if (shoeService.count(new LambdaQueryWrapper<ShoePo>().eq(ShoePo::getOrderId, removeShoeRequest.getOrderId())) == 0) {
            //卸除鞋子的时候要去释放鞋架和鞋架使用数量
            releasesGridNew(removeShoeRequest.getOrderId());
        }
        return R.ok(true);
    }


    @ApiOperation("订单入库--new")
    @PostMapping("/orderIn/new")
    @Transactional
    public R<Boolean> orderInNew(@RequestBody @Valid ShoeCheckInDto shoeUpdateDto) {
        OrderPo orderPo = orderService.getById(shoeUpdateDto.getOrderId());
        if (orderPo == null) {
            throw new WashException("订单不存在");
        }
        ShopPo shopPo = shopService.getById(orderPo.getShopId());
        List<ShoePo> shoePoList = new ArrayList<>();
        ShoeImgDto shoeImgDto = shoeUpdateDto.getShoeImgDtoList().get(0);
        ShoePo shoePo = shoeService.getById(shoeImgDto.getShoeId());
        //验证图片是否上传,不允许为null
        shoeUpdateDto.validate();
        // 设置鞋子的图片
        shoePo.setPicture(CollectionUtil.join(shoeUpdateDto.getShoeImgDtoList().stream().map(ShoeImgDto::getShoeImg).collect(Collectors.toList()), ","));
        shoePo.setWashType(shoeImgDto.getWashType());
        //设置物品类型
        shoePo.setItemType(shoeUpdateDto.getItemType());
        // 设置鞋子为清洗中
        shoePo.setStatus(1);
        shoePo.setRemark(JSONUtil.toJsonStr(shoeUpdateDto.getRemark()));
        shoePoList.add(shoePo);

        // 入库-取鞋中 带入库都能入库
        if (Objects.equals(orderPo.getStatus(), OrderStatusEnum.PENDING_STORAGE.getStatus()) || Objects.equals(orderPo.getStatus(), OrderStatusEnum.PICK_UP_SHOES.getStatus())) {
            if (!shoeUpdateDto.getShoeImgDtoList().isEmpty()) {
                orderPo.setShopRemark(shoeUpdateDto.getShoeImgDtoList().get(0).getShopRemark());
            }

/*            orderPo.setCheckInPerson(AdminUserUtil.getLoginUserName());
            orderPo.setCheckInTime(new Date());
//            orderPo.setFittingImg(shoeUpdateDto.getFittingImg());//附件图片需要单独存一个表
            orderPo.setStatus(OrderStatusEnum.CLEANING_IN_PROCESS.getStatus());
            // 抖音核销
            dyServiceUpdateRequest.updateFullFill(orderPo, 4); TODO 20250909 by jjz 拆分入库接口,分入库和确认人库，在确认入库的时候去调用抖音核销和修改订单状态*/
            orderService.updateById(orderPo);
            shoeService.updateBatchById(shoePoList);
            //删除之前的配饰
            iAccessoriesService.remove(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, orderPo.getId()).eq(AccessoriesPo::getBizId, shoePoList.get(0).getId()));
            if (CollectionUtil.isNotEmpty(shoeUpdateDto.getAccessorieRecords())) {
                List<AccessoriesPo> accessoriesPoList = new ArrayList<>();
                shoeUpdateDto.getAccessorieRecords().forEach(accessorieRecord -> {
                    AccessoriesPo accessoriesPo = new AccessoriesPo();
                    accessoriesPo.setOrderId(orderPo.getId());
                    //设置鞋子的id
                    accessoriesPo.setBizId(shoePoList.get(0).getId());
                    //调用获取配饰的水洗码
                    String washCode = CodeUtil.getPWashCodeNext("P", shopPo.getShopCode());
                    accessoriesPo.setWashCode(/*accessorieRecord.getWashCode()*/washCode);
                    accessoriesPo.setType(accessorieRecord.getItemType());
                    accessoriesPo.setUrl(StringUtils.join(accessorieRecord.getImages(), ","));
                    accessoriesPo.setStatus(0);//默认 0 未质检
                    accessoriesPoList.add(accessoriesPo);
                });

                iAccessoriesService.saveBatch(accessoriesPoList);//判断是否有配饰,有的话 就保存配饰数据
            }


            // 如果是线上的订单，mt的订单,就需要更新美团的状态为衣服清洗中
            /**if (orderPo.getComeFrom().equals("2")) {
             log.info("更新美团的物流信息为 [清洗中(洗衣)]:" + orderPo.getCustomPhone());
             mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.CLEANING, "刷鞋匠", "13892920924");
             }TODO 20250909 by jjz 拆分入库接口,分入库和确认人库，在确认入库的时候去调用抖音核销和修改订单状态*/
            return R.ok(true);
        } else {
            return R.fail("订单状态不为【待入库】或【取鞋中】状态，无法进行入库!!");
        }

    }

    @ApiOperation("根据订单id占用货架格子")
    @GetMapping("/bindRackGridPo")
    public R bindRackGridPo(@ApiParam(value = "订单id") @RequestParam("orderId") @Valid @NotEmpty(message = "订单id不能为空") String orderId) {
        OrderPo orderPo = orderService.getById(orderId);
        String factoryId = orderPo.getFactoryId();
        String lockKey = "shoeRack:lock" + factoryId;
        RLock lock = null;
        try {
            lock = redissonClient.getLock(lockKey);
            // 尝试获取锁，等待最多10秒，锁定时间为30秒
            boolean isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
            if (!isLocked) {
                log.error("获取分布式锁失败，店铺ID：" + factoryId);
                return R.fail("入库失败，请稍后重试");
            }
            // 获取工厂的架子格子
            List<FactoryshelvesRackGridPo> factoryshelvesRackGridPoList = factoryshelvesRackGridService.shareGridList(1, factoryId, orderPo.getId());// 所有的放同一个格子
            if (factoryshelvesRackGridPoList.isEmpty()) {
                throw new WashException("鞋架已经用完,不能分配鞋架");
            }
            // 鞋子添加鞋架的编号
            FactoryshelvesRackGridPo shoeRackGridPo = factoryshelvesRackGridPoList.get(0);//所有的鞋子都放同一个格子
            shoeRackGridPo.setOrderId(orderPo.getId());
            factoryshelvesRackGridService.saveOrUpdate(shoeRackGridPo);//格子和订单绑定
            lock.unlock();
            return R.ok(shoeRackGridPo);
        } catch (Exception e) {
            log.error("获取分布式锁异常，orderId：" + orderId, e);
        }
        return R.fail();
    }

    @ApiOperation(value = "确认入库", notes = "确认入库,修改订单状态和调用抖音核销")
    @PostMapping("/orderIn/confim")
    public R<String> orderInConfim(@RequestBody @Valid OrderConfimCheckInDto orderInConfimDto) {
        OrderPo orderPo = orderService.getById(orderInConfimDto.getOrderId());
        if (orderPo == null) {
            throw new WashException("订单不存在");
        }
        //清除未入库的鞋子
        Assert.isTrue(shoeService.count(new LambdaQueryWrapper<ShoePo>().eq(ShoePo::getOrderId, orderInConfimDto.getOrderId()).eq(ShoePo::getStatus, 0).isNull(ShoePo::getItemType)) == 0, "该订单下物品类型中有不完整商品，请检查");
        //确认入库操作
        if (OrderConfimCheckInDto.ACTION_CONFIRM.equals(orderInConfimDto.getAction())) {
            Integer beforeStatus = orderPo.getStatus();
            // 全局分布式锁key
            RLock lock = null;
            String factoryId = orderPo.getFactoryId();
            if (StringUtils.isEmpty(factoryId)) {
                log.info("线上订单入库没有工厂id,请检查orderId:{}", orderInConfimDto.getOrderId());
            }
            String lockKey = "shoeRack:lock" + orderPo.getFactoryId();
            try {
                lock = redissonClient.getLock(lockKey);
                // 尝试获取锁，等待最多10秒，锁定时间为30秒
                boolean isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
                if (!isLocked) {
                    log.error("获取分布式锁失败，店铺ID：" + factoryId);
                    return R.fail("入库失败，请稍后重试");
                }

                log.info("线上订单入库获取到分布式锁,店铺ID：" + factoryId);
                // 获取工厂的架子格子
                List<FactoryshelvesRackGridPo> factoryshelvesRackGridPoList = factoryshelvesRackGridService.list(new LambdaQueryWrapper<FactoryshelvesRackGridPo>().eq(FactoryshelvesRackGridPo::getOrderId, orderPo.getId())) /*factoryshelvesRackGridService.shareGridList(1, factoryId, orderPo.getId())*/;// 所有的放同一个格子
//                List<FactoryshelvesRackGridPo> factoryshelvesRackGridPoList = factoryshelvesRackGridService.shareGridList(1, factoryId);
                if (factoryshelvesRackGridPoList.isEmpty()) {
                    throw new WashException("鞋架已经用完,不能分配鞋架");
                }
                // 获取数据库的店铺
                ShopPo shopDb = shopService.getById(orderPo.getShopId());
                if (shopDb == null) {
                    throw new WashException("门店不存在，请检查门店");
                }
                List<ShoePo> shoePoList = shoeService.getByOrderId(orderPo.getId());

                // 鞋子添加鞋架的编号
                FactoryshelvesRackGridPo shoeRackGridPo = factoryshelvesRackGridPoList.get(0);// 所有的鞋子都放同一个格子
                //订单和格子绑定
                for (ShoePo shoePo : shoePoList) {
                    shoePo.setSrgId(shoeRackGridPo.getId());
                    shoePo.setSrgCode(shoeRackGridPo.getShowCode());
                }
                shoeRackGridPo.setOrderId(orderPo.getId());
                shoeService.saveOrUpdateBatch(shoePoList);
                factoryshelvesRackGridService.saveOrUpdate(shoeRackGridPo);//格子和订单绑定
                orderPo.setCheckInPerson(AdminUserUtil.getLoginUserName());
                orderPo.setCheckInTime(new Date());
                orderPo.setStatus(OrderStatusEnum.CLEANING_IN_PROCESS.getStatus());
                orderPo.setShoeNum(shoePoList.size());
                orderService.updateById(orderPo);
                int updateNum = factoryShelvesService.updateUseNumInteger(shoeRackGridPo.getFactoryshelvesId());
                log.info("facotyshelves ｛｝: updateUseNumInteger :{}", shoeRackGridPo.getFactoryshelvesId(), updateNum);
                // 抖音核销
                if (!OrderStatusEnum.CLEANING_IN_PROCESS.getStatus().equals(beforeStatus)) {
                    dyServiceUpdateRequest.updateFullFill(orderPo, 4);
                }
                orderService.updateById(orderPo);

                // 如果是线上的订单，mt的订单,就需要更新美团的状态为衣服清洗中
                if (orderPo.getComeFrom().equals("2")) {
                    log.info("更新美团的物流信息为 [清洗中(洗衣)]:" + orderPo.getCustomPhone());
                    mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.CLEANING, "刷鞋匠", "13892920924");
                }

            } catch (Exception e) {
                log.error("确认入库异常", e);
                throw new WashException("确认入库异常");
            } finally {
                if (lock != null) {
                    lock.unlock();
                }
            }
        } else {
            //TODO   取消入库需要做那些操作?
            //取消入库 把录入的配饰信息删掉
/*            iAccessoriesService.remove(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, orderPo.getId()));
            shoeService.remove(new LambdaQueryWrapper<ShoePo>().eq(ShoePo::getOrderId, orderPo.getId()));TODO 和前端商量把取消去掉，由调用一个个的删除*/
            //取消入库只是把订单改成入库前的状态,让操作员可以新添加鞋子
            //判断是否有已质检的数据
            long qualityInspectionCount = qualityInspectionService.count(new LambdaQueryWrapper<QualityInspectionPo>().eq(QualityInspectionPo::getOrderId, orderPo.getId()).eq(QualityInspectionPo::getStatus, 1));
            //订单状态为清洗中且没有质检数据，就回退成待入库,其他情况就不去重置订单状态
            if (OrderStatusEnum.CLEANING_IN_PROCESS.getStatus().equals(orderPo.getStatus()) && qualityInspectionCount == 0) {
                orderPo.setStatus(OrderStatusEnum.PENDING_STORAGE.getStatus());
                orderService.updateById(orderPo);
            }
        }

        return R.ok();
    }

    @Autowired
    private QualityInspectionServiceImpl qualityInspectionService;

    @PostMapping("/getWashCode")
    @ApiOperation(value = "获取水洗码", notes = "获取水洗码 1.物品  2配饰")
    public R<GetWashCodeResp> getWashCode(@RequestBody @Valid GetWashCodeDto washCodeDto) {
        ShopPo shopPo = shopService.getById(washCodeDto.getShopId());
        Assert.notNull(shopPo, "门店不存在");
        String code = null;
        GetWashCodeResp washCodeResp = new GetWashCodeResp();
        OrderPo orderPo = orderService.getById(washCodeDto.getOrderId());
        List<Integer> orderStatusList = Lists.newArrayList(OrderStatusEnum.PICK_UP_SHOES.getStatus(), OrderStatusEnum.PENDING_STORAGE.getStatus());
        Assert.isTrue(orderStatusList.contains(orderPo.getStatus()) /*== 2*/, "订单状态不为【待入库/取鞋中】状态，无法进行水洗码生成!!");
        //判断是否是配饰
        if (washCodeDto.isAccessories()) {
            //调用获取配饰的水洗码
            code = CodeUtil.getPWashCodeNext("P", shopPo.getShopCode());
        } else {
            CustomIdGenerator customIdGenerator = new CustomIdGenerator();
            washCodeResp.setShoeId(String.valueOf(customIdGenerator.nextId(null)));


            ShoePo shoePo = new ShoePo();
            shoePo.setId(washCodeResp.getShoeId());
/*            shoePo.setSrgId(shoeRackGridPo.getId());
            shoePo.setSrgCode(shoeRackGridPo.getShowCode());*/
            shoePo.setShopId(shopPo.getId());
            code = CodeUtil.getWashCodeNext(shopPo.getId(), shopPo.getShopCode());
            log.info("wash code is {}", code);
            shoePo.setWashCode(code);
            // 定单号的生成规则
            shoePo.setOrderNumber(orderPo.getOrderNo());
            shoePo.setOrderId(orderPo.getId());
            shoePo.setWashType(null);
            // 待清洗
            shoePo.setStatus(0);
            shoePo.setPhone(orderPo.getCustomPhone());
            shoePo.setStorageTime(new Date());
            shoePo.setStorageUser(AdminUserUtil.getUserId());
            shoePo.setStorageUserName(AdminUserUtil.getLoginUserName());
            shoeService.save(shoePo);
        }
        washCodeResp.setWashCode(code);
        return R.ok(washCodeResp);
    }


    @Autowired
    private IAccessoriesService iAccessoriesService;

    @ApiOperation("订单入库")
    @PostMapping("/orderIn")
    @Transactional
    public R<Boolean> orderIn(@RequestBody ShoeUpdateDto shoeUpdateDto) {

        List<ShoePo> shoePoList = new ArrayList<>(shoeUpdateDto.getShoeImgDtoList().size());
        for (ShoeImgDto shoeImgDto : shoeUpdateDto.getShoeImgDtoList()) {
            ShoePo shoePo = shoeService.getById(shoeImgDto.getShoeId());
            // 设置鞋子的图片
            shoePo.setPicture(shoeImgDto.getShoeImg());
            shoePo.setWashType(shoeImgDto.getWashType());
            // 设置鞋子为清洗中
            shoePo.setStatus(1);
            shoePoList.add(shoePo);
        }
        OrderPo orderPo = orderService.getById(shoeUpdateDto.getOrderId());
        if (orderPo == null) {
            throw new WashException("订单不存在");
        }
        // 入库-取鞋中 带入库都能入库
        if (Objects.equals(orderPo.getStatus(), OrderStatusEnum.PENDING_STORAGE.getStatus()) || Objects.equals(orderPo.getStatus(), OrderStatusEnum.PICK_UP_SHOES.getStatus())) {
            if (!shoeUpdateDto.getShoeImgDtoList().isEmpty()) {
                orderPo.setShopRemark(shoeUpdateDto.getShoeImgDtoList().get(0).getShopRemark());
            }

            orderPo.setCheckInPerson(AdminUserUtil.getLoginUserName());
            orderPo.setCheckInTime(new Date());
            orderPo.setFittingImg(shoeUpdateDto.getFittingImg());
            orderPo.setStatus(OrderStatusEnum.CLEANING_IN_PROCESS.getStatus());
            // 抖音核销
            dyServiceUpdateRequest.updateFullFill(orderPo, 4);
            orderService.updateById(orderPo);
            shoeService.updateBatchById(shoePoList);
            // 如果是线上的订单，mt的订单,就需要更新美团的状态为衣服清洗中
            if (orderPo.getComeFrom().equals("2")) {
                log.info("更新美团的物流信息为 [清洗中(洗衣)]:" + orderPo.getCustomPhone());
                mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.CLEANING, "刷鞋匠", "13892920924");
            }
            return R.ok(true);
        } else {
            return R.fail("订单状态不为【待入库】或【取鞋中】状态，无法进行入库!!");
        }

    }


    //修改增加查询条件 by jjz 2023/09/07
    @ApiOperation("入库记录")
    @PostMapping("/checkInList")
    public R<Page<OrderDetailVo>> checkInList(/*String searchString*/@RequestBody CheckInQuery checkInQuery) {
        Page<OrderDetailVo> page = orderService.checkInList(checkInQuery);
        return R.ok(page);
    }

    @ApiOperation("出库记录")
    @PostMapping("/checkOutList")
    public R<Page<OrderDetailVo>> checkOutList(@RequestBody CheckOutDto checkOutDto) {

        OrderPo orderPoWashCode = getOrderByWashCode(checkOutDto.getSearchString(), 5);
        if (orderPoWashCode == null) {
            orderPoWashCode = getOrderByWashCode(checkOutDto.getSearchString(), 6);
        }
        Page<OrderDetailVo> page;
        if (orderPoWashCode != null) {
            page = new Page<>();
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            BeanUtils.copyProperties(orderPoWashCode, orderDetailVo);
            page.setRecords(Collections.singletonList(orderDetailVo));
            page.setTotal(1);
            return R.ok(page);
        }
        page = orderService.checkOutList(checkOutDto);
        return R.ok(page);
    }

    @ApiOperation("订单统计，每个状态订单的数量")
    @PostMapping("/orderCount")
    public R<HashMap> orderCount() {
        HashMap map = orderService.orderCount();
        return R.ok(map);
    }

    @ApiOperation("给线上的订单分配鞋架,只要分配就会清空以前的分配数据")
    @GetMapping("/shareGrid")
    @Transactional // TODO 修改分配鞋架传工厂id进来分配
    public R<List<ShoePo>> shareGrid(String orderId, Integer shoesNum) {
        CodeUtil.clearCurrentCacheCode();
        OrderPo orderPo = orderService.getById(orderId);
        if (orderPo == null) {
            throw new WashException("订单不存在，请仔细检查");
        }
        // 全局分布式锁key
        RLock lock = null;
        String factoryId = orderPo.getFactoryId();
        if (StringUtils.isEmpty(factoryId)) {
            log.info("线上订单入库没有工厂id,请检查orderId:{}", orderId);
        }
        String lockKey = "shoeRack:lock" + orderPo.getFactoryId();
        try {
            lock = redissonClient.getLock(lockKey);
            // 尝试获取锁，等待最多10秒，锁定时间为30秒
            boolean isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
            if (!isLocked) {
                log.error("获取分布式锁失败，店铺ID：" + factoryId);
                return R.fail("入库失败，请稍后重试");
            }

            log.info("线上订单入库获取到分布式锁,店铺ID：" + factoryId);
            /*  2025年8月25日 22:24:15  修改走工厂的货架   List<ShoeRackGridPo> shoeRackGridPoList = shoeRackGridService.shareGridList(shoesNum, orderPo.getShopId());
            
            if (shoeRackGridPoList.isEmpty()) {
                throw new WashException("鞋架已经用完,不能分配鞋架");
            }*/
            List<FactoryshelvesRackGridPo> factoryshelvesRackGridPoList =
                    factoryshelvesRackGridService.shareGridList(1, factoryId, orderId);// 所有的放同一个格子
            if (factoryshelvesRackGridPoList.isEmpty()) {
                throw new WashException("鞋架已经用完,不能分配鞋架");
            }
            // 获取数据库的店铺
            ShopPo shopDb = shopService.getById(orderPo.getShopId());
            if (shopDb == null) {
                throw new WashException("门店不存在，请检查门店");
            }
            // 查询以前的数据,并且删除
            List<ShoePo> shoePoList = shoeService.getByOrderId(orderPo.getId());
            if (!shoePoList.isEmpty()) {
                shoeService.removeBatchByIds(shoePoList);
            }
            // 清空鞋架
            for (ShoePo shoePo : shoePoList) {
                ShoeRackGridPo shoeRackGridPo = shoeRackGridService.getByShoeId(shoePo.getId());
                if (shoeRackGridPo != null) {
                    shoeRackGridPo.setShoeId(null);
                    shoeRackGridService.updateById(shoeRackGridPo);
                }
            }
            // 鞋子添加鞋架的编号
            List<ShoePo> tempShoeList = new ArrayList<>();
            // for (ShoeRackGridPo shoeRackGridPo : shoeRackGridPoList) {
            // for (FactoryshelvesRackGridPo shoeRackGridPo : factoryshelvesRackGridPoList) {
            FactoryshelvesRackGridPo shoeRackGridPo = factoryshelvesRackGridPoList.get(0);// 所有的鞋子都放同一个格子
            for (int i = 0; i < shoesNum; i++) {
                ShoePo shoePo = new ShoePo();
                shoePo.setSrgId(shoeRackGridPo.getId());
                shoePo.setSrgCode(shoeRackGridPo.getShowCode());
                shoePo.setShopId(shopDb.getId());
                String nextCode = CodeUtil.getWashCodeNext(shopDb.getId(), shopDb.getShopCode());
                log.info("wash code is {}", nextCode);
                shoePo.setWashCode(nextCode);
                // 定单号的生成规则
                shoePo.setOrderNumber(orderPo.getOrderNo());
                shoePo.setOrderId(orderPo.getId());
                shoePo.setWashType(null);
                // 待清洗
                shoePo.setStatus(0);
                shoePo.setPhone(orderPo.getCustomPhone());
                shoePo.setStorageTime(new Date());
                shoePo.setStorageUser(AdminUserUtil.getUserId());
                shoePo.setStorageUserName(AdminUserUtil.getLoginUserName());
                tempShoeList.add(shoePo);
            }
            shoeService.saveBatch(tempShoeList);
            shoeRackGridPo.setOrderId(orderPo.getId());
            factoryshelvesRackGridService.updateById(shoeRackGridPo);// 设置订单id
            /*    for (int i = 0; i < tempShoeList.size(); i++) {
                ShoeRackGridPo shoeRackGridPo = shoeRackGridPoList.get(i);
                ShoePo shoePo = tempShoeList.get(i);
                shoeRackGridPo.setShoeId(shoePo.getId());
            }
              shoeRackGridService.updateBatchById(shoeRackGridPoList);
            */
            // 更新鞋架的使用数量
            int updateNum = factoryShelvesService.updateUseNumInteger(shoeRackGridPo.getFactoryshelvesId());
            log.info("facotyshelves ｛｝: updateUseNumInteger :{}", shoeRackGridPo.getFactoryshelvesId(), updateNum);
            // shoeRackService.updateUseNum(shoeRackGridPoList);
            //
            orderPo.setShoeNum(shoesNum);
            orderService.updateById(orderPo);
            return R.ok(tempShoeList);
        } catch (Exception e) {
            log.error(e);
            throw new WashException("入库失败: " + e.getMessage(), e);
        } finally {
            if (lock != null && lock.isHeldByCurrentThread()) {
                lock.unlock(); // 确保释放锁
            }
        }
    }

    @ApiOperation("添加鞋子")
    @GetMapping("/shareGridAddShoe")
    @Transactional
    public R<List<ShoePo>> shareGridAddShoe(String orderId, Integer shoesNum) {
        CodeUtil.clearCurrentCacheCode();
        OrderPo orderPo = orderService.getById(orderId);
        if (orderPo == null) {
            throw new WashException("订单不存在，请仔细检查");
        }
        // 2025年8月18日 20：00 修改货架格子按订单分配 by jjz
        // List<ShoeRackGridPo> shoeRackGridPoList = shoeRackGridService.shareGridList(/*shoesNum*/1,
        // orderPo.getShopId());
        // 2025年8月18日 20：00 添加工厂货架格子按订单分配 by jjz
        List<FactoryshelvesRackGridPo> factoryshelvesRackGridPoList =
                factoryshelvesRackGridService.shareGridList(1, orderPo.getFactoryId(), orderId);
        /*    if (shoeRackGridPoList.isEmpty()) {
            throw new WashException("鞋架已经用完,不能分配鞋架");
        }*/

        if (factoryshelvesRackGridPoList.isEmpty()) {
            throw new WashException("鞋架已经用完,不能分配鞋架");
        }

        // 获取数据库的店铺
        ShopPo shopDb = shopService.getById(orderPo.getShopId());
        if (shopDb == null) {
            throw new WashException("门店不存在，请检查门店");
        }
        // 鞋子添加鞋架的编号
        List<ShoePo> tempShoeList = new ArrayList<>();
        Set<String> factoryshelvesIdSet = new HashSet<>();
        FactoryshelvesRackGridPo shoeRackGridPo = factoryshelvesRackGridPoList.get(0);// 所有的鞋子都放同一个格子
        for (int i = 0; i < /*shoeRackGridPoList*/shoesNum; i++) {
            // ShoeRackGridPo shoeRackGridPo = shoeRackGridPoList.get(i);

            ShoePo shoePo = new ShoePo();
            shoePo.setSrgId(shoeRackGridPo.getId());
            shoePo.setSrgCode(shoeRackGridPo.getShowCode());
            shoePo.setShopId(shopDb.getId());
            String nextCode = CodeUtil.getWashCodeNext(shopDb.getId(), shopDb.getShopCode());
            log.info("wash code is {}", nextCode);
            shoePo.setWashCode(nextCode);
            // 定单号的生成规则
            shoePo.setOrderNumber(orderPo.getOrderNo());
            shoePo.setOrderId(orderPo.getId());
            shoePo.setWashType(null);
            // 待清洗
            shoePo.setStatus(0);
            shoePo.setPhone(orderPo.getCustomPhone());
            shoePo.setStorageTime(new Date());
            shoePo.setStorageUser(AdminUserUtil.getUserId());
            shoePo.setStorageUserName(AdminUserUtil.getLoginUserName());
            tempShoeList.add(shoePo);
            factoryshelvesIdSet.add(shoeRackGridPo.getFactoryshelvesId());
        }
        shoeService.saveBatch(tempShoeList);

        /* for (int i = 0; i < tempShoeList.size(); i++) {
            // ShoeRackGridPo shoeRackGridPo = shoeRackGridPoList.get(i);
            FactoryshelvesRackGridPo shoeRackGridPo1 = factoryshelvesRackGridPoList.get(i);
            ShoePo shoePo = tempShoeList.get(i);
            shoeRackGridPo1.setOrderId(shoePo.getOrderId());
        }*/
        // 给格子设置orderid
        for (FactoryshelvesRackGridPo data : factoryshelvesRackGridPoList) {
            data.setOrderId(orderId);
        }
        // shoeRackGridService.updateBatchById(shoeRackGridPoList);
        factoryshelvesRackGridService.updateBatchById(factoryshelvesRackGridPoList);
        // 更新鞋架的使用数量
        // shoeRackService.updateUseNum(shoeRackGridPoList);
        // 循环去根据货架的使用数量 by jjz
        factoryshelvesIdSet.forEach(e -> {
            factoryShelvesMapper.updateUseNumInteger(e);
        });

        //
        orderPo.setShoeNum(orderPo.getShoeNum() + shoesNum);
        orderService.updateById(orderPo);
        return R.ok(tempShoeList);
    }

    @ApiOperation("取消订单")
    @PostMapping("/cancelOrder")
    @Transactional
    public R<OrderPo> cancelOrder(String orderId) {
        OrderPo orderPo = orderService.getById(orderId);
        // 查询以前的数据,并且删除
        List<ShoePo> shoePoList = shoeService.getByOrderId(orderPo.getId());
        if (!shoePoList.isEmpty()) {
            shoeService.removeBatchByIds(shoePoList);
        }
        // 清空鞋架
        for (ShoePo shoePo : shoePoList) {
            ShoeRackGridPo shoeRackGridPo = shoeRackGridService.getByShoeId(shoePo.getId());
            if (shoeRackGridPo != null) {
                shoeRackGridPo.setShoeId(null);
                shoeRackGridService.updateById(shoeRackGridPo);
            }
        }

        // 计算使用的数量鞋架
        List<String> rackIds = shoePoList.stream().map(ShoePo::getSrgId).distinct().collect(Collectors.toList());
        for (String rackId : rackIds) {
            shoeRackService.updateUseNumInteger(rackId);
        }

        orderPo.setStatus(OrderStatusEnum.CANCEL.getStatus());
        orderService.updateById(orderPo);
        return R.ok(orderPo);
    }

    /**
     * @author lijianguo
     * @Date 22/09/2024 反洗
     **/
    @ApiOperation("反洗订单")
    @PostMapping("/returnWashOrder")
    @Transactional
    public R<OrderPo> returnWashOrder(@RequestBody ReturnWashDto returnWashDto) throws LopException {
        OrderPo orderPo = orderService.getById(returnWashDto.getOrderId());
        if (orderPo == null) {
            throw new WashException("原始订单不存在");
        }
        if (returnWashDto.getWashIdLIst().isEmpty()) {
            throw new WashException("水洗");
        }
        List<ShoePo> shoePoList = new ArrayList<>(returnWashDto.getWashIdLIst().size());
        for (String shoeId : returnWashDto.getWashIdLIst()) {
            shoePoList.add(shoeService.getById(shoeId));
        }
        // 查询反洗的商品
        ShopGoodsPo shopGoodsPo = shopGoodsService.getReturnGoods("返洗");
        if (shopGoodsPo == null) {
            throw new WashException("返洗商品不存在，请新建返洗商品");
        }
        OrderGoodPo orderGoodPo = new OrderGoodPo();
        orderGoodPo.setGoodsId(shopGoodsPo.getId());
        orderGoodPo.setBuyNum(returnWashDto.getWashIdLIst().size());
        orderGoodPo.setShopGoodsUrl(shopGoodsPo.getUrl());

        AddOrderVo addOrderVo = new AddOrderVo();
        addOrderVo.setShoesNum(returnWashDto.getWashIdLIst().size());
        addOrderVo.setShopId(orderPo.getShopId());
        addOrderVo.setCustomPhone(orderPo.getCustomPhone());
        addOrderVo.setOrderGoodPoList(Collections.singletonList(orderGoodPo));
        addOrderVo.setComeFrom(orderPo.getComeFrom());
        addOrderVo.setTotalPrice(0D);
        addOrderVo.setOrderPrice(0D);
        addOrderVo.setDiscountRatio(0D);
        addOrderVo.setShoeCollectionDate(returnWashDto.getGetShoeTime());
        addOrderVo.setShopRemark(returnWashDto.getShopRemark());
        addOrderVo.setPre("R");
        addOrderVo.setBrandId(orderPo.getBrandId());
        // 添加订单
        OrderPo orderNew = pcSaveUpdate(addOrderVo).getData();
        orderNew.setFactoryId(orderPo.getFactoryId());//fix bug 反洗得也需要填写原来的工厂id
        orderNew.setMtOrderId(orderPo.getMtOrderId());
        orderNew.setBrandId(orderPo.getBrandId());
        orderNew.setMtSerialNumbers(orderPo.getMtSerialNumbers());
        orderNew.setMtUniOrderId(orderPo.getMtUniOrderId());
        orderNew.setWashFactory(orderPo.getWashFactory());
        orderNew.setWashShop(orderPo.getWashShop());
        orderNew.setCustomId(orderPo.getCustomId());
        // 如果是线上的订单还需要发京东的物流
        if (!orderPo.getComeFrom().equals("1")) {
            // 以前的物流信息
            OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderId(orderPo.getId());
            // 上面查出来的物流为送鞋,如果物流状态不对，就不能下单，需要手动下单
            if (Objects.isNull(orderTransportPo) || !StringUtils.equals(orderTransportPo.getType(), "送鞋")) {
                throw new WashException("用户取件地址不正确，请联系用户手动下单!!!");
            }

            // 需要把东西从用户哪里寄过来
            MtUserAddress send = new MtUserAddress();
            send.setReceiverMobile(orderTransportPo.getReceiverMobile());
            send.setReceiverName(orderTransportPo.getReceiverName());
            send.setReceiverAddress(orderTransportPo.getReceiverFullAddress());
            // 接收
            MtUserAddress receive = new MtUserAddress();
            receive.setReceiverMobile(orderTransportPo.getSendMobile());
            receive.setReceiverName(orderTransportPo.getSendName());
            receive.setReceiverAddress(orderTransportPo.getSendFullAddress());
            jdCreateOrder.process(orderNew, send, receive, "取鞋", returnWashDto.getReserveTime());
            // 设置状态为取鞋中
            orderNew.setStatus(OrderStatusEnum.PICK_UP_SHOES.getStatus());
        }
        orderService.updateById(orderNew);
        log.info("===订单的反洗===");
        return R.ok(orderNew);
    }

    /*
    此方法废弃，判断不完整！！！！！用MtMerchantCancelOrder里面的取消！！！！
    @ApiOperation("美团取消线上的订单")
    @GetMapping("/mtCancelOrder")
    public R<String> mtCancleOrder(String orderId) {
    
        OrderPo orderPo = orderService.getById(orderId);
        if (!orderPo.getComeFrom().equals("2")){
            throw new WashException("只能取消美团的订单");
        }
        // 美团的取消
        mtUpdateFulFillInfo.shopCancelOrder(orderId);
        orderPo.setStatus(0);
    
        orderService.updateById(orderPo);
        return R.ok();
    }
    */

    @ApiOperation("取消小程序的订单")
    @PostMapping("/cancelXcx")
    public R<OrderPo> cancelXcx(String orderId, String remark) {
        log.info("管理员取消 {}", orderId);
        return R.ok(orderService.cancel(orderId, "管理员取消"));
    }

    @ApiOperation("更新订单的备注")
    @GetMapping("/updateRemark")
    public R<OrderPo> updateRemark(String orderId, String shopRemark) {
        log.info("更新订单的备注 {} {}", orderId, shopRemark);
        OrderPo orderPo = orderService.getById(orderId);
        orderPo.setShopRemark(shopRemark);
        orderService.updateById(orderPo);
        return R.ok();
    }

    @ApiOperation("美团履约完成的信息")
    @GetMapping("/fulFillMtStatus")
    public R<String> fulFillMtStatus(String orderId) {
        log.info("美团履约完成的信息 {}", orderId);
        OrderPo orderPo = orderService.getById(orderId);
        long betTime = (new Date().getTime() - orderPo.getCreateTime().getTime()) / (1000 * 3600 * 24);
        if (betTime < 2) {
            throw new WashException("只能处理二天以前的订单");
        }
        if (!orderPo.getComeFrom().equals("2")) {
            throw new WashException("只能处理美团的订单");
        }
        // 获取订单的状态
        FulFillEnum fulFillEnum = mtUpdateFulFillInfo.getMtOrderStatus(orderPo);
        orderPo.setFulfillStatus(fulFillEnum.getCode());
        orderService.updateById(orderPo);
        if (FulFillEnum.COMPLETION.equals(fulFillEnum)) {
            throw new WashException("该订单已经处理完成了");
        }
        // 处理为已经完成
        mtUpdateFulFillInfo.fulfillInfo(orderId, FulFillEnum.COMPLETION, "刷鞋匠", "13892920924");
        return R.ok(fulFillEnum.getCode());
    }

    /**
     * 修正订单表上的
     *
     * @param correctOrderRequest 修正请求
     * @return
     */
    @ApiOperation("订单的修正")
    @PostMapping("/correct")
    public R correctOrder(@Valid @RequestBody CorrectOrderRequest correctOrderRequest) {
        //设置order表上的 brand_id wash_factory_id wash_factory wash_shop
        //一批分50条
        List<List<String>> data = CollectionUtil.split(correctOrderRequest.getOrderNos(), 50);

//        for(List<String> list : data){
        for (String orderNo : correctOrderRequest.getOrderNos()) {
            OrderPo orderPo = orderService.getByOrderNo(orderNo);
            Assert.notNull(orderPo, "订单不存在");
            ShopPo shopPo = shopService.getById(orderPo.getShopId());
            FactoryPo factoryPo = factoryAddressHelper.getFactoryAddressWithShopAddress(shopPo.getProvincesName(), shopPo.getCityName(), shopPo.getCountryName(), orderPo.getBrandId());
            Assert.notNull(factoryPo, "工厂不存在:省:" + shopPo.getProvincesName() + ",市:" + shopPo.getCityName() + ",brandId:" + orderPo.getBrandId());
            orderPo.setFactoryId(factoryPo.getId());
            orderPo.setBrandId(shopPo.getBrandId());
            BrandPo brandPo = brandService.getById(shopPo.getBrandId());
            orderPo.setWashFactory(factoryPo.getFactoryName());
            orderPo.setSelfOperated(Objects.isNull(brandPo) ? 0 : brandPo.getSelfOperated());
            orderPo.setWashShop(shopPo.getShopName());
            orderService.updateById(orderPo);
//            }
        }
        return R.ok();
    }

    @ApiOperation("测试抖音创建预约单")
    @GetMapping("/testDyCreateBook")
    public R testDyCreateBook(Long orderId) {
        OrderPo orderPo = orderService.getById(orderId);
        dyBookRequest.createBookPost(orderPo);
        return R.ok();
    }

    @Autowired
    private DyBookRequest dyBookRequest;
}